import { getOrderList, getOrderAuditorList, getFinalsList, delOrder } from "~/api/order";

import { getFinalsSettlement } from "~/api/finals"

import { getMyInfo } from "~/api/user";

//获取列表
async function getOrderByasync(axios, store, status) {
  let res = await getOrderList(axios, status);
  let obj = {
    loading: false,
    strTime: '',
    endOrderData: [],
    mergeArr: []
  };
  obj.roleID = store.state.user.role_id;

  if (res.data.code == 200) {
    obj.total = res.data.page.total;
    obj.tableData = res.data.data;

    obj.pageSize = res.data.page.per_page;
    obj.tableSize = res.data.page.per_page;
    obj.tableEnd = res.data.page.per_page;
    //有数据
    if (obj.tableData.length > 0) {
      for (let i in obj.tableData) {
        //审核文件 切割数组
        if (
          obj.tableData[i].review_file == null ||
          obj.tableData[i].review_file == ""
        ) { } else {
          obj.tableData[i].reviewfileArr = [];
          let reviewfile = obj.tableData[i].review_file.split("&");
          for (let j in reviewfile) {
            let itemobj = {
              id: j + 1,
              path: reviewfile[j],
              file: ''
            };
            let itemArr = itemobj.path.split("/")
            itemobj.path = itemArr[itemArr.length - 1]
            itemobj.file = itemArr.slice(0, 2).join("/");
            obj.tableData[i].reviewfileArr.push(itemobj);
          }
        }
        // 徒弟审核文件
        if (
          obj.tableData[i].student_review_file == null ||
          obj.tableData[i].student_review_file == ""
        ) { } else {
          obj.tableData[i].studentReviewFile = [];
          let reviewfile = obj.tableData[i].student_review_file.split("&");
          for (let j in reviewfile) {
            let itemobj = {
              id: j + 1,
              path: reviewfile[j],
              file: ''
            };
            let itemArr = itemobj.path.split("/")
            itemobj.path = itemArr[itemArr.length - 1]
            itemobj.file = itemArr.slice(0, 2).join("/");
            obj.tableData[i].studentReviewFile.push(itemobj);
          }
        }

        //已完成文件 切分组件
        if (
          obj.tableData[i].fish_file == null ||
          obj.tableData[i].fish_file == ""
        ) { } else {
          obj.tableData[i].fishfileArr = [];
          let fishfile_Arr = obj.tableData[i].fish_file.split("&");
          for (let f in fishfile_Arr) {
            let itemobj = {
              id: f + 1,
              path: fishfile_Arr[f],
              file: ''
            };
            let itemArr = itemobj.path.split("/")
            itemobj.path = itemArr[itemArr.length - 1]
            itemobj.file = itemArr.slice(0, 2).join("/");
            obj.tableData[i].fishfileArr.push(itemobj);
          }
        }

        if (status.status == '等待提交国知局') {
          //判断有没有final_orders
          if (obj.tableData[i].final_orders.length > 0) {
            obj.mergeArr.push(obj.tableData[i].final_orders.length)
            let itemTable = obj.tableData[i].final_orders
            for (const key in itemTable) {
              let item = '';
              item = {
                order_number: itemTable[key].order_number,
                patent_name: itemTable[key].name,
                type: itemTable[key].type,
                status: itemTable[key].status,
                application_number: itemTable[key].application_number,
                organization: itemTable[key].organization,
                submit_at: itemTable[key].submit_at,
              }
              obj.endOrderData.push(item)
            }
          }
        }
      }
    }
  }

  if (obj.roleID) {
    let myInfo = await getMyInfo(axios);
    if (myInfo.data.status == 'success') {
      obj.myInfo = myInfo.data.data
      store.commit("setRoleInfo", myInfo.data.data)
    }
  }
  return obj;
}

async function getFinalsOrder(axios, store, status) {
  let res = await getFinalsList(axios, status);
  let obj = {
    loading: false,
    strTime: '',
    endOrderData: [],
    mergeArr: []
  };
  obj.roleID = store.state.user.role_id;
  if (res.data.code == 200) {
    obj.total = res.data.page.total;
    obj.tableData = res.data.data;
    obj.pageSize = res.data.page.per_page;
    obj.tableSize = res.data.page.per_page;
    obj.tableEnd = res.data.page.per_page

    // if (from == 'fromProcessed') {
    //   obj.realMoneyTotal = res.data.money_total.real_money
    //   obj.settlementsPriceMoney = res.data.money_total.settlements_price_money
    //   obj.deductionMoney = res.data.money_total.deduction_money
    //   obj.rewardMoney = res.data.money_total.reward_money
    // }

    //有数据
    if (obj.tableData.length > 0) {
      for (let i in obj.tableData) {
        if (obj.tableData[i].order) {
          if (obj.tableData[i].order.fish_file == null || obj.tableData[i].order.fish_file == "") { }
          else {
            obj.tableData[i].order.fishfileArr = [];
            let fishfile_Arr = obj.tableData[i].order.fish_file.split("&");
            for (let f in fishfile_Arr) {
              let itemobj = {
                id: f + 1,
                path: fishfile_Arr[f],
                file: ''
              };
              let itemArr = itemobj.path.split("/")
              itemobj.path = itemArr[itemArr.length - 1]
              itemobj.file = itemArr.slice(0, 2).join("/");
              obj.tableData[i].order.fishfileArr.push(itemobj);
            }
          }
        }
      }
    }
  }

  if (obj.roleID) {
    let myInfo = await getMyInfo(axios);
    if (myInfo.data.status == 'success') {
      obj.myInfo = myInfo.data.data
      store.commit("setRoleInfo", myInfo.data.data)
    }
  }
  return obj;
}

async function getOrderAuditor(axios, store, status = {}) {
  status.status = '案件内审中'
  status.auditor_id = store.state.user.id
  let res = await getOrderAuditorList(axios, status);
  let obj = {
    loading: false,
    strTime: '',
    endOrderData: [],
    mergeArr: [],
    myInfo: {}
  };
  obj.roleID = store.state.user.role_id;
  if (res.data.code == 200) {
    obj.total = res.data.page.total;
    obj.tableData = res.data.data;
    obj.pageSize = res.data.page.per_page;
    obj.tableSize = res.data.page.per_page;
    obj.tableEnd = res.data.page.per_page;
    let tableData = [];
    //有数据
    if (obj.tableData.length > 0) {
      for (var i in obj.tableData) {
        let item = obj.tableData[i]
        obj.tableData[i].is_read = true
        if (item.opinions.length > 0) {
          if (item.opinions.some(v => v.is_read == 2)) {
            obj.tableData[i].is_read = false
          }
        }
        //审核文件 切割数组
        if (
          obj.tableData[i].review_file == null ||
          obj.tableData[i].review_file == ""
        ) { } else {
          obj.tableData[i].reviewfileArr = [];
          let reviewfile = obj.tableData[i].review_file.split("&");
          for (var j in reviewfile) {
            let itemobj = {
              id: j + 1,
              path: reviewfile[j],
              file: ''
            };
            // let itemArr = itemobj.path.split("/")
            // itemobj.path = itemArr[itemArr.length - 1]
            // itemobj.file = itemArr.slice(0, 2).join("/");
            obj.tableData[i].reviewfileArr.push(itemobj);
          }
        }

        //已完成文件 切分组件
        if (
          obj.tableData[i].fish_file == null ||
          obj.tableData[i].fish_file == ""
        ) { } else {
          obj.tableData[i].fishfileArr = [];
          let fishfile_Arr = obj.tableData[i].fish_file.split("&");
          for (var f in fishfile_Arr) {
            let itemobj = {
              id: f + 1,
              path: fishfile_Arr[f],
              file: ''
            };
            let itemArr = itemobj.path.split("/")
            itemobj.path = itemArr[itemArr.length - 1]
            itemobj.file = itemArr.slice(0, 2).join("/");
            obj.tableData[i].fishfileArr.push(itemobj);
          }
        }
      }
    }
    // obj.myInfo.waitAuditor = res.data.page.total
    if (obj.roleID) {
      let myInfo = await getMyInfo(axios);
      if (myInfo.data.status == 'success') {
        obj.myInfo = myInfo.data.data
        store.commit("setRoleInfo", myInfo.data.data)
      }
    }
    // store.commit("setRoleInfo", myInfo.data.data)
  }
  return obj;
}

async function getOrderRepair(axios, store, status = {}) {
  status.status = '案件修改中'
  status.auditor_id = store.state.user.id
  let res = await getOrderAuditorList(axios, status);
  let obj = {
    loading: false,
    strTime: '',
    endOrderData: [],
    mergeArr: [],
    myInfo: {}
  };
  obj.roleID = store.state.user.role_id;
  if (res.data.code == 200) {
    obj.total = res.data.page.total;
    obj.tableData = res.data.data;
    obj.pageSize = res.data.page.per_page;
    obj.tableSize = res.data.page.per_page;
    obj.tableEnd = res.data.page.per_page;
    //有数据
    if (obj.tableData.length > 0) {
      for (var i in obj.tableData) {
        //审核文件 切割数组
        if (
          obj.tableData[i].review_file == null ||
          obj.tableData[i].review_file == ""
        ) { } else {
          obj.tableData[i].reviewfileArr = [];
          let reviewfile = obj.tableData[i].review_file.split("&");
          for (var j in reviewfile) {
            let itemobj = {
              id: j + 1,
              path: reviewfile[j],
              file: ''
            };
            obj.tableData[i].reviewfileArr.push(itemobj);
          }
        }

        //已完成文件 切分组件
        if (obj.tableData[i].fish_file == null || obj.tableData[i].fish_file == "") { } else {
          obj.tableData[i].fishfileArr = [];
          let fishfile_Arr = obj.tableData[i].fish_file.split("&");
          for (var f in fishfile_Arr) {
            let itemobj = {
              id: f + 1,
              path: fishfile_Arr[f],
              file: ''
            };
            let itemArr = itemobj.path.split("/")
            itemobj.path = itemArr[itemArr.length - 1]
            itemobj.file = itemArr.slice(0, 2).join("/");
            obj.tableData[i].fishfileArr.push(itemobj);
          }
        }
      }
    }
    // obj.myInfo.waitRepair = obj.total
    if (obj.roleID) {
      let myInfo = await getMyInfo(axios);
      if (myInfo.data.status == 'success') {
        obj.myInfo = myInfo.data.data
        store.commit("setRoleInfo", myInfo.data.data)
      }
    }
    // store.commit("setRoleInfo", obj.myInfo.data.data)
    // obj.roleID = this.$store.state.user.id
  }
  return obj;
}

//刷新数据
function getData(axios, status, that) {
  getOrderList(axios, status).then(res => {
    if (res.data.code == 200) {
      that.currentPage = 1;
      that.tableData = res.data.data;
      that.total = res.data.page.total
      that.pageSize = res.data.page.per_page;
      that.tableSize = res.data.page.per_page;
      that.tableEnd = res.data.page.per_page;
      //有数据
      if (that.tableData.length > 0) {
        for (var i in that.tableData) {
          //审核文件 切割数组
          if (
            that.tableData[i].review_file == null ||
            that.tableData[i].review_file == ""
          ) { } else {
            that.tableData[i].reviewfileArr = [];

            let reviewfile = that.tableData[i].review_file.split("&");
            for (var j in reviewfile) {
              let itemobj = {
                id: j + 1,
                path: reviewfile[j],
                file: ''
              };
              let itemArr = itemobj.path.split("/")
              itemobj.path = itemArr[itemArr.length - 1]
              itemobj.file = itemArr.slice(0, 2).join("/");
              that.tableData[i].reviewfileArr.push(itemobj);
            }
          }
          //已完成文件 切分组件
          if (
            that.tableData[i].fish_file == null ||
            that.tableData[i].fish_file == ""
          ) { } else {
            that.tableData[i].fishfileArr = [];
            let fishfile_Arr = that.tableData[i].fish_file.split("&");
            for (var f in fishfile_Arr) {
              let itemobj = {
                id: f + 1,
                path: fishfile_Arr[f],
                file: ''
              };
              let itemArr = itemobj.path.split("/")
              itemobj.path = itemArr[itemArr.length - 1]
              itemobj.file = itemArr.slice(0, 2).join("/");
              that.tableData[i].fishfileArr.push(itemobj);
            }
          }

          if (status.status == '等待提交国知局') {
            //判断有没有final_orders
            if (obj.tableData[i].final_orders.length > 0) {
              obj.mergeArr.push(obj.tableData[i].final_orders.length)
              let itemTable = obj.tableData[i].final_orders
              for (const key in itemTable) {
                let item = '';
                item = {
                  order_number: itemTable[key].order_number,
                  patent_name: itemTable[key].name,
                  type: itemTable[key].type,
                  status: itemTable[key].status,
                  application_number: itemTable[key].application_number,
                  organization: itemTable[key].organization,
                  submit_at: itemTable[key].submit_at,
                }
                obj.endOrderData.push(item)
              }
            }
          }
        }
      }
      if (that.roleID == 2) {
        getMyInfo(axios).then(({ data }) => {
          if (data.status == 'success') {
            that.myInfo = data.data
            that.$store.commit("setRoleInfo", data.data)
          } else {
            console.log(err)
          }
        })
          .catch(err => {
            console.log(err)
          })
      }
    }
  });
}

function delOrderByJS(axios, id, status, that) {
  that.$confirm("是否确定删除此订单", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      delOrder(axios, id)
        .then(({ data }) => {
          if (data.status == "success") {
            that.$message.success("删除成功");
            getData(axios, status, that);
          } else {
            that.$message.error(data.message);
          }
        })
        .catch(err => {
          that.$message.error(err);
        });
    })
    .catch(() => {
      that.$message({
        type: "info",
        message: "已取消删除"
      });
    });
}

// 获取处理时长
function getProcessingTime(val, id) {
  let statusArr = val.statuss;
  let createDay = "";
  for (const i in statusArr) {
    if (statusArr[i].id == id) {
      if (statusArr[i].pivot.created_at) {
        createDay = statusArr[i].pivot.created_at
      } else {
        createDay = val.created_at
      }

    }
  }
  if (statusArr) {
    if (statusArr.length == 0) {
      createDay = val.created_at
    }
  }

  //获取接单的时间戳
  createDay = createDay.replace(/-/g, "/");
  var createTime = new Date(createDay).getTime();
  //获取当前的时间戳
  var nowTime = new Date().getTime();
  //获取处理时间戳
  let cha = nowTime - createTime;

  function IsNaN(value) {
    return typeof value === 'number' && isNaN(value);
  }
  if (IsNaN(cha)) {
    return ''
  }
  //转换天数
  let day = Math.floor(cha / 1000 / 60 / 60 / 24);
  let processingTime = day + "天";
  if (day <= 0) {
    //不够一天显示小时
    let hour = Math.round((cha / 1000 / 60 / 60) % 24);
    processingTime = hour + "小时";
  }
  return processingTime;
}

// 获取答复列表
async function getAnswerList (axios, store, data) {
  let res = await getFinalsList(axios, data)
  let dataObj = {
    loading: false,
    tableData: [],
    total: 0,
    pageSize: 0,
  }
  if (res.data.code == 200) {
    dataObj.tableData = splitFile(res.data.data)
    dataObj.total = res.data.page.total
    dataObj.pageSize = res.data.page.per_page
    dataObj.tableSize = Number(res.data.page.per_page)
    dataObj.currentPage = res.data.page.current_page
  }
  dataObj.roleID = store.state.user.role_id
  if (dataObj.roleID) {
    let myInfo = await getMyInfo(axios)
    if (myInfo.data.status == 'success') {
      dataObj.myInfo = myInfo.data.data
      store.commit("setRoleInfo", myInfo.data.data)
    }
  }
  return dataObj
}

function splitFile (data) {
  if (data.length > 0) {
    for (let i in data) {
      //审核文件 切割数组

      if (data[i].opinion_file) {
        data[i].opinionFile = [];
        let reviewfile = data[i].opinion_file.split("&");
        for (let j in reviewfile) {
          let itemobj = {
              id: j + 1,
              path: reviewfile[j],
              file: ''
          };
          let itemArr = itemobj.path.split("/")
          itemobj.path = itemArr[itemArr.length - 1]
          itemobj.file = itemArr.slice(0, 2).join("/");
          data[i].opinionFile.push(itemobj);
        }
      }
      if (data[i].answer_file) {
        data[i].answerFile = [];
        let reviewfile = data[i].answer_file.split("&");
        for (let j in reviewfile) {
          let itemobj = {
              id: j + 1,
              path: reviewfile[j],
              file: ''
          };
          let itemArr = itemobj.path.split("/")
          itemobj.path = itemArr[itemArr.length - 1]
          itemobj.file = itemArr.slice(0, 2).join("/");
          data[i].answerFile.push(itemobj);
        }
      }

    }
  }
  return data
}

// 获取结算列表
async function getSettlementList(axios, store, status) {
  let res = await getFinalsSettlement(axios, status);
  let obj = {
    loading: false,
    strTime: '',
    endOrderData: [],
    mergeArr: []
  };
  obj.roleID = store.state.user.role_id;
  if (res.data.code == 200) {
    // console.log(res.data.data)
    obj.total = res.data.page.total;
    obj.tableData = res.data.data;
    obj.pageSize = res.data.page.per_page;
    obj.tableSize = res.data.page.per_page;
    obj.tableEnd = res.data.page.per_page
    if(res.data.money_total) {
      obj.realMoneyTotal = res.data.money_total.real_money
      obj.settlementsPriceMoney = res.data.money_total.settlements_price_money
      obj.deductionMoney = res.data.money_total.deduction_money
      obj.rewardMoney = res.data.money_total.reward_money
    }
  }


  //   if (from == 'fromProcessed') {
  //
  //   }

  // }

  if (obj.roleID) {
    let myInfo = await getMyInfo(axios);
    if (myInfo.data.status == 'success') {
      obj.myInfo = myInfo.data.data
      store.commit("setRoleInfo", myInfo.data.data)
    }
  }
  return obj;
}

export default {
  getOrderByasync,
  getData,
  delOrderByJS,
  getProcessingTime,
  getOrderAuditor,
  getOrderRepair,
  getFinalsOrder,
  getAnswerList,
  getSettlementList
}
